# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:张广勤
@Web site: https://www.tunan.wang
@Github:www.github.com
 
@File:chrome_test7_0.py
@Time:2024/11/3 15:37

@Motto:不积跬步无以至千里，不积小流无以成江海！
"""

from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
# from selenium.common import TimeoutException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from time import sleep
import os
import sys

# from selenium.webdriver.support.wait import WebDriverWait

# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
a_txt_DIR = os.path.join(BASE_DIR,"a.txt")
# print(BASE_DIR)
# print(a_txt_DIR)
driver_DIR = os.path.join(BASE_DIR,"chromedriver.exe")
print(driver_DIR)

def convert_to_seconds(time_str):
    # 分割字符串获取分钟和秒
    parts = time_str.split('分')
    minutes = int(parts[0])  # 将分钟转换为整数
    seconds = int(parts[1].replace('秒', ''))  # 移除"秒"并转换为整数

    # 将分钟转换为秒，并加上秒
    total_seconds = minutes * 60 + seconds
    return total_seconds


def daojishi(n):
    # 设置倒计时时间（秒）
    countdown_time = n * 60  # 5分钟
    while countdown_time > 0:
        minutes, seconds = divmod(countdown_time, 60)
        # 使用 \r 回到行首，end='' 防止换行
        print(f"\r倒计时: {minutes:02}:{seconds:02}", end='')
        sleep(1)
        countdown_time -= 1
    print("\n倒计时结束！")


def read_credentials():
    if os.path.exists(a_txt_DIR):
        with open(a_txt_DIR, 'r') as file:
            username = file.readline().strip()
            password = file.readline().strip()
            return username, password
    return None, None

def write_credentials(username, password):
    with open(a_txt_DIR, 'w') as file:
        file.write(username + '\n')
        file.write(password + '\n')


# 指定 ChromeDriver 的路径
# driver_path = 'd:/code_zgq/ganbu/chromedriver.exe'
driver_path = driver_DIR
service = Service(executable_path=driver_path)

# 创建 WebDriver 实例
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(5)
driver.maximize_window()

# 打开网页
driver.get('https://www.sxgbxx.gov.cn/login')

username, password = read_credentials()
if not username or not password:
    username = input("请输入用户名: ")
    password = input("请输入密码: ")
    write_credentials(username, password)

# 找到用户名输入框并输入用户名
driver.find_element(By.ID, 'userEmail').send_keys(username)
# 找到密码输入框并输入密码
driver.find_element(By.ID, 'userPassword').send_keys(password)
# 提示用户输入验证码
# # 找到用户名输入框并输入用户名
# driver.find_element(By.ID, 'userEmail').send_keys('u0122092')
# # 找到密码输入框并输入密码
# driver.find_element(By.ID, 'userPassword').send_keys('071726zgq001!')
# 提示用户输入验证码
# input("按回车继续...")
daojishi(1/2)  #30秒
# 设置最长等待时间为10秒
# wait = WebDriverWait(driver, 30)

# 循环直到找到“登录”按钮或者超时
# while True:
#     try:
#         # 尝试找到“登录”按钮并点击
#         login_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "body > div.in-wrap > div.nxb-box > div.bg-fa.of > section > div > article > section > section > div:nth-child(3) > a")))
#         login_button.click()
#         break  # 如果点击成功，跳出循环
#     except TimeoutException:
#         # 如果在等待时间内没有找到“登录”按钮，继续循环
#         print("Login button not found, retrying...")
# 专题 首页-好干部在线-山西干部在线学院
# //*[@id="aCoursesList"]/div[1]/div[3]/div[2]/ul/li[1]/div/a/div/img
#                                    #aCoursesList > div.container > div.mt30.m-top-box.tzc_zt_dbox > div.net-cou-box > ul > li:nth-child(1) > div > a > div > img
driver.find_element(By.CSS_SELECTOR,"#aCoursesList > div.container > div.mt30.m-top-box.tzc_zt_dbox > div.net-cou-box > ul > li:nth-child(1) > div > a > div > img").click()
print(driver.title)# 点击后转到立即学习 党的二十届三中全会精神网络培训专题-好干部在线-山西干部在线学院
sleep(3)
all_handles = driver.window_handles
driver.switch_to.window(all_handles[-1])
# driver.get(driver.current_url)
# 立即学习
# 党的二十届三中全会精神网络培训专题-好干部在线-山西干部在线学院
# //*[@id="aCoursesList"]/div/div[1]/article[2]/div/div[4]/div/a
#                                    #aCoursesList > div > div.i-box.clearfix.pr.of.mt20.m-video-box > article.fl.c-a-wrap.cou-a-wrap > div > div.mt20.clearfix.of > div > a
driver.find_element(By.CSS_SELECTOR,"#aCoursesList > div > div.i-box.clearfix.pr.of.mt20.m-video-box > article.fl.c-a-wrap.cou-a-wrap > div > div.mt20.clearfix.of > div > a").click()
sleep(3)
print(driver.title)# 点击后转到计划详情-好干部在线-山西干部在线学院

# 计划详情-好干部在线-山西干部在线学院
# 继续学习
all_handles = driver.window_handles
driver.switch_to.window(all_handles[0])# [0] 当前页，学习贯彻党的二十届三中全会精神-好干部在线-山西干部在线学院
driver.get(driver.current_url)
# driver.current_window_handle
# /html/body/div[1]/div[1]/div[4]/section[2]/div/div/article/div[2]/section/div[1]/div/div[2]/ul/li[1]/aside/a
#                                    body > div.in-wrap > div.nxb-box.ucenter-box > div.bg-fa.of > section.container > div > div > article > div.i-box.mt20 > section > div.p-l-wrap > div > div.p-cou-wrap.p-l-module > ul > li:nth-child(1) > aside > a
#                                    body > div.in-wrap > div.nxb-box.ucenter-box > div.bg-fa.of > section.container > div > div > article > div.i-box.mt20 > section > div.p-l-wrap > div > div.p-cou-wrap.p-l-module > ul > li:nth-child(1) > aside > a
# driver.get("https://www.sxgbxx.gov.cn/front/couinfo/870a4f1201e8d51e")
# driver.get("https://www.sxgbxx.gov.cn/front/playkpoint/870a4f1201e8d51e")
kechengs = driver.find_elements(By.CSS_SELECTOR,"div.p-cou-wrap.p-l-module > ul >li")
print(len(kechengs))
for i in range(len(kechengs)):
    for handle in driver.window_handles:
        # 先切换到该窗口
        driver.switch_to.window(handle)
        # 得到该窗口的标题栏字符串，判断是不是我们要操作的那个窗口
        if '计划详情' in driver.title:
            # 如果是，那么这时候WebDriver对象就是对应的该该窗口，正好，跳出循环，
            break
    kecheng = f"body > div.in-wrap > div.nxb-box.ucenter-box > div.bg-fa.of > section.container > div > div > article > div.i-box.mt20 > section > div.p-l-wrap > div > div.p-cou-wrap.p-l-module > ul > li:nth-child({i+1}) > aside > a"
    driver.find_element(By.CSS_SELECTOR,kecheng).click()
    sleep(3)
    # driver.switch_to.window(all_handles[-1])
    all_handles = driver.window_handles
    driver.switch_to.window(all_handles[-1])
    driver.get(driver.current_url)
    print(driver.title)



    # 学习贯彻党的二十届三中全会精神-好干部在线-山西干部在线学院
    # //*[@id="aCoursesList"]/div/div[1]/article[2]/div/div[4]/div/a
    # #aCoursesList > div > div.i-box.clearfix.pr.of.mt20.m-video-box > article.fl.c-a-wrap.cou-a-wrap > div > div.mt20.clearfix.of > div > a
    driver.find_element(By.CSS_SELECTOR,"#aCoursesList > div > div.i-box.clearfix.pr.of.mt20.m-video-box > article.fl.c-a-wrap.cou-a-wrap > div > div.mt20.clearfix.of > div > a").click()
    print(driver.title)
    sleep(3)

    all_handles = driver.window_handles
    driver.switch_to.window(all_handles[-1])
    # driver.get(driver.current_url)
    # driver.get("https://www.sxgbxx.gov.cn/front/playkpoint/870a4f1201e8d51e")
    # # //*[@id="kp_2"]
    # print(driver.title)
    elements =driver.find_elements(By.CSS_SELECTOR,"article.n-ct-cont-menu > div > div")
    print(len(elements))
    for i in range(len(elements)):
        str_kp = f'//*[@id="kp_{i+1}"]'
        # print(str)
        element = driver.find_element(By.XPATH,str_kp)
        a_tag = element.find_element(By.XPATH,"./div/a[2]")
        if a_tag.get_attribute("title")=='图文播放':
            a_tag.click()
            # sleep(10)
            # print(a_tag.get_attribute("title"))
            # print(a_tag.text)
            print("播放图文。。。。。。。。。。。。。。。。。")
            # for i in range(0, 2000, 100):
            #     js_code = "var q=document.documentElement.scrollTop=" + str(i)
            #     driver.execute_script(js_code)
            #     # sleep(10)
            daojishi(1 / 6)
        # //*[@id="kp_1"]/div/a[1]/span
        # //*[@id="kp_1"]/div/a[2]
    #


        # element = driver.find_element(By.XPATH,'//*[@id="kp_2"]')
        # # print(element)
        # a_tag = element.find_element(By.XPATH,"./div/a[2]")
        # print(a_tag)
        elif a_tag.get_attribute("title")=='视频播放':
            a_tag.click()
            # print(a_tag.get_attribute("title"))
            # play = driver.find_element(By.CSS_SELECTOR, "div.pv-cover > span")
            # play.click()
            play = driver.find_element(By.XPATH,'//*[@id="video_box"]/div/div[1]/div[5]/span').click()
            print('播放视频》》》》》》》》》》》》》》》》》》')
            duration = driver.find_element(By.CSS_SELECTOR,
                                           f"#kp_{i+1} > div > a.play-icon-box > small")  # kp_1 > div > a.play-icon-box > small
            print(duration.text)
            # sleep(convert_to_seconds(duration.text)+3)
            # sleep(20)
            daojishi((convert_to_seconds(duration.text)+3)/60)

    # print(element)
    # print(element.text)
    driver.close()




print("到了")
driver.quit()
